package com.grm.distributed.lock.service;

import com.grm.distributed.lock.common.Result;
import com.grm.distributed.lock.mapper.ProductMapper;
import com.grm.distributed.lock.pojo.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * redis 扣减库存 count=count-1,再set,会出现并发问题
 */
@Slf4j
@Service
public class ProductService4 {
    @Autowired
    private ProductMapper productMapper;

    // RedisTemplate会配置默认的JDK序列化器，以二进制存储，会乱码，StringRedisTemplate会配置成String，方便调试
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public Result sell() {
        // 1. 查库存
        String productCountStr = stringRedisTemplate.opsForValue().get("product_count");
        Integer count = Integer.valueOf(productCountStr);
        // 2. 扣减库存
        if(count > 0){
            count = count - 1;
        }
        log.info("product current count = {}",count);
        stringRedisTemplate.opsForValue().set("product_count",String.valueOf(count));
        return Result.success(count);
    }
}
